package com.situ.company.interceptor;

import com.situ.company.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// Interceptor拦截器能实现：浏览器过来的所有请求首先经过拦截器
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这里判断用户有没有登录，如果登录就返回true放行，
        // 如果没有登录，就返回false，跳转到登录界面
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        if (user == null) {// 用户没有凭证，没有登录
            response.sendRedirect("/login.jsp");
            return false;
        } else {
            // 有凭证，已经登录
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
